import { fileURLToPath, URL } from 'node:url';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';
import UnoCSS from 'unocss/vite';

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'node:path';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_GLOB_NAMESPACE } = env;
  return {
    css: {
      preprocessorOptions: {
        less: {
          additionalData: `@import "${resolve('src/assets/styles/config.less')}";`,
          modifyVars: {
            namespace: VITE_GLOB_NAMESPACE,
          },
          javascriptEnabled: true,
        },
      },
    },
    plugins: [
      vue(),
      UnoCSS(),
      // 自动化引入naive-ui
      AutoImport({
        imports: [
          'vue',
          {
            'naive-ui': ['useDialog', 'useMessage', 'useNotification', 'useLoadingBar'],
          },
        ],
      }),
      Components({
        resolvers: [NaiveUiResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '#': fileURLToPath(new URL('./types', import.meta.url)),
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    server: {
      host: '0.0.0.0', // 默认为localhost
      port: 7001, // 端口号
      open: false, // 是否自动打开浏览器
      proxy: {
        // 本地开发环境通过代理实现跨域，生产环境使用 nginx 转发
        '/dev-api': {
          target: 'http://localhost:3000', // 后端服务实际地址
          changeOrigin: true,
          //rewrite: (path) => path.replace(/^\/dev-api/, ""),
          rewrite: (path) => path.replace(new RegExp('^' + env.VITE_APP_BASE_API), ''),
        },
      },
    },
  };
});
